% Copyright (C) 2009,2010,2011,2012  Marco Restelli
%
% This file is part of:
%   LDGH -- Local Hybridizable Discontinuous Galerkin toolkit
%
% LDGH is free software: you can redistribute it and/or modify it
% under the terms of the GNU General Public License as published by
% the Free Software Foundation, either version 3 of the License, or
% (at your option) any later version.
%
% LDGH is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
% or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
% License for more details.
%
% You should have received a copy of the GNU General Public License
% along with LDGH. If not, see <http://www.gnu.org/licenses/>.
%
% author: Marco Restelli                   <marco.restelli@gmail.com>


function PV_cgdd_series (inname, fname, itime, N, outfile)

  %% PV_cgdd_series(inname, fname, itime, N, outfile)
  %%
  %% Call PV_cgdd for a series of files and prepare a .pvd file to
  %% collect the generated vtk files.
  %%
  %% fname nust contain a '%' to indicate the subdomain number and a '$'
  %% to indicate the suffix 'grid', 'base' or 'res-XXXX'.

  %% make sure required packages are loaded
  pkg load fpl

  %% Summary file
  fid = fopen ([outfile, ".pvd"], "w");
 
  line = {"<?xml version=\"1.0\"?>";
          ["<VTKFile type=\"Collection\" ", ...
           "version=\"0.1\" byte_order=\"BigEndian\">"];
          "<Collection>"};

  fprintf (fid, "%s\n", line{:});

  %% Part loop
  for j=1:length(itime)

    for i=0:N

      if(N>0)
        Npos = strfind (fname, "%")(1);
        fnameN = sprintf ("%s%.3i%s", 
                          fname(1:Npos-1), 
                          i, 
                          fname(Npos+1:end));
      else
        fnameN = fname;
      end
     

      Xpos = strfind (fnameN, "$")(1);

      fnameNX = sprintf ("%sres-%.4i%s", fnameN(1:Xpos-1),
                         itime(j), 
                         fnameN(Xpos+1:end));

      res = load (fnameNX);
      if(N>0)
        msh = load (sprintf ("%s.%.3d", inname, i), 
                    "p", "t");
      else
        msh = load (inname, "p", "t");
      endif
      
      fnameNX = sprintf ("%s-%.3i-%.4i", outfile, i, itime(j));

      PV_cgdd (msh, 
               [res.nnn, res.ppp, ...
                res.vvv, res.n_d, res.n_a], 
               fnameNX);
      
      fprintf (fid, ["  <DataSet timestep=\"%17.17g\" ", ...
               "group=\"\" part=\"%i\" file=\"%s\"/>\n"], 
               res.time, i, 
               sprintf ("%s.vtu", fnameNX));

     endfor
   end

   line = {" </Collection>";
           "</VTKFile>"};
   fprintf (fid, "%s\n", line{:});
   
   fclose(fid);

endfunction

